package com.platform.api;

import com.platform.annotation.IgnoreAuth;
import com.platform.entity.ApiResourceVo;
import com.platform.entity.ApiShareBillEntity;
import com.platform.entity.UserVo;
import com.platform.service.ApiResourceService;
import com.platform.service.ApiShareBillService;
import com.platform.service.ApiUserService;
import com.platform.service.TokenService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.CharUtil;
import com.platform.utils.R;
import com.platform.utils.RRException;
import com.platform.utils.ResourceUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import java.io.InputStream;
import java.util.Random;

/**
 * API登录授权
 *
 * @author 朱如森
 */
@RestController
@RequestMapping("/api/auth")
public class ApiAuthController extends ApiBaseAction {

    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private ApiUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ApiResourceService apiResourceService;
    @Autowired
    private ApiShareBillService apiShareBillService;

    @IgnoreAuth
    @RequestMapping("openShare")
    public R openShare(HttpServletRequest request, Long channel, Long userId, Long agentId) throws Exception {
        String ua = request.getHeader("User-Agent").toLowerCase();

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));

        ApiShareBillEntity info = new ApiShareBillEntity();

        String ip = request.getRemoteAddr();
        if (ip != null) {
            info.setIp(this.getClientIp());
//            info.setIpAddress(this.getAddresses(ip));
        }

        if (channel != null) {
            info.setChannel(channel);
        }
        if (userId != null) {
            info.setUserId(userId);
        }
        info.setUcid(String.valueOf(userAgent.getId()));
        info.setBrowser(ua);

        info.setPlatform(userAgent.getOperatingSystem().getName());

        info.setAppCodeName(userAgent.getBrowser().toString());
        info.setCreateTimeView(new Date());
        apiShareBillService.save(info);
        return R.ok(0, "请求成功", "");
    }


    /**
     * 苹果举报 接口
     *
     * @param content
     * @return
     */
    @IgnoreAuth
    @RequestMapping("tipster")
    public R tipster(String content) {
        return R.ok(0, "提交成功", "");
    }


    @IgnoreAuth
    @RequestMapping("downloadShare")
    public R downloadShare(Long userId, String sign) throws Exception {


        return R.ok(0, "请求成功", "");
    }


    /**
     * 注册
     *
     * @param mobile
     * @return
     */
    @IgnoreAuth
    @RequestMapping("login")
    public R register(String mobile, Long userId, Long channel, Long agentId, String deviceToken,
                      String mobileType) throws Exception {
        UserVo userVo = userService.queryByMobile(mobile);
        Date nowTime = new Date();
        if (userVo != null) {
            userVo.setLast_login_ip(userVo.getRegister_ip());
            userVo.setLast_login_time(userVo.getRegister_time());
            userVo.setDevice_token(deviceToken);
            userVo.setMobile_type(mobileType);
            userService.update(userVo);
        } else {
            userVo = new UserVo();
            userVo.setAgent(agentId);
            userVo.setUsername(CharUtil.getRandomString(12));
            userVo.setRegister_time(nowTime);
            userVo.setAvailable_amount(new BigDecimal(0));
            userVo.setPresent_amount(new BigDecimal(0));
            userVo.setWithdraw_amount(new BigDecimal(0));
            userVo.setContribution(new BigDecimal(0));
            userVo.setMobile(mobile);
            userVo.setCity_id(1L);
            userVo.setRegister_ip(this.getClientIp());
            userVo.setLast_login_ip(userVo.getRegister_ip());
            userVo.setLast_login_time(userVo.getRegister_time());
            userVo.setDevice_token(deviceToken);
            userVo.setMobile_type(mobileType);
            userVo.setOlinetime(new BigDecimal(0));
            userVo.setNickname("窝客" + mobile.substring(7, 11));
            if (userId != null) {
                userVo.setConnection(userId);
            }

            if (channel != null) {
                userVo.setChannel(channel);
            }
            userService.save(userVo);
        }

        Map<String, Object> tokenMap = tokenService.createToken(userVo);

        String token = MapUtils.getString(tokenMap, "token");

        Map<String, Object> data = new HashMap();
        data.put("token", token);

        return R.ok(0, "请求成功", data);
    }

    /**
     * 上传文件
     */
    @IgnoreAuth
    @RequestMapping("/upload")
    public R appUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());


        String savePath = ResourceUtil.getConfigByName("file_address");

        /**
         *  文件大小
         */
        Long fileSize = file.getSize();
        if (fileSize > 100000000) {
//            throw new Exception("上传失败：文件大小不能超过10M");
            return R.ok(1, "上传失败：文件大小不能超过100M", "");
        }

        /**
         * 得到文件名称
         */
        String fileName = file.getOriginalFilename();

        String newFileName = "";
        String fileExt = "";

        String saveFileName = ymd;

        savePath += File.separator + ymd + File.separator;
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }


        if (fileSize > 0) {
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                /**
                 *  文件后缀
                 */
                fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

                /**
                 * 重定义文件名
                 */
                newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

                SaveFileFromInputStream(file.getInputStream(), savePath, newFileName);


            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        } else {
//            throw new Exception("上传失败：上传文件不能为�空");
            return R.ok(1, "上传失败：上传文件不能为空", "");
        }


        /**
         * 保存入库
         */
        ApiResourceVo resourceVo = new ApiResourceVo();
        resourceVo.setIsShow(0);
        saveFileName += File.separator + newFileName;
        resourceVo.setUrl(saveFileName);
        apiResourceService.save(resourceVo);

        Map<String, Object> objectMap = new HashMap<>();

        objectMap.put("id", resourceVo.getId());
        objectMap.put("url", resourceVo.getUrl());


        return R.ok(0, "上传成功", objectMap);
    }

    public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        FileOutputStream fs = new FileOutputStream(path + filename);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }
}
